package com.example.administrator.exkotlin.multithread

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Binder
import android.os.Build
import android.os.IBinder
import androidx.core.app.NotificationCompat
import android.util.Log
import com.example.administrator.exkotlin.MainActivity
import java.lang.Exception

/**
 * service例子
 * */
class MyService : Service() {
    private val TAG = "MyService"

    lateinit var thread: Thread
    private val mMyRunnable = MyRunnable()

    lateinit var serviceCallback: ServiceCallback
    private var count = 0
    private var threadStatus = false
    val foregroundChannelId = "前台服务1"

    companion object {
        var isRunning = false
        var isBinding = false
    }

    public interface ServiceCallback {
        fun porgeress(progress: Int)
    }

    class MyBind(private val myService: MyService) : Binder() {
        fun getService(): MyService {

            return myService
        }
    }

    //绑定完成通信
    override fun onBind(intent: Intent): IBinder {
        Log.i(TAG, "startBind")
        return MyBind(this)
    }

    //开启线程
    fun startThread(serviceCallback: ServiceCallback) {
        Log.i(TAG, "click startThread")
        this.serviceCallback = serviceCallback
        threadStatus = true
        if (!::thread.isInitialized) {
            thread = Thread(mMyRunnable)
            thread.start()
        } else if (thread.isAlive) {
            thread.interrupt()
            thread = Thread(mMyRunnable)
            thread.start()
        }
    }

    fun stopThread() {
        threadStatus = false
        if (::thread.isInitialized && thread.isAlive) {
            thread.interrupt()
            Log.i(TAG, "Runnable interrupt")
        }
    }

    inner class MyRunnable : Runnable {
        override fun run() {
            Log.i(TAG, "Runnable start")
            while (threadStatus) {
                try {
                    synchronized(count) {
                        count++
                    }
                    Log.i(TAG, "" + count)
                    if (::serviceCallback.isInitialized) {
                        serviceCallback.porgeress(count)
                    }
                    Thread.sleep(500)
                } catch (e: Exception) {

                }
            }
        }

    }

    fun getServiceStatus(): String = if (isRunning) {
        "服务正在运行"
    } else {
        "服务已经停止"
    }

    /**
     * 只在第一次启动的时候调用
     * */
    override fun onCreate() {
        super.onCreate()
        isRunning = true
        Log.i(TAG, "onCreate")
        starForeServeice()
    }

    /**
     * 开启前台服务
     * 8.0之后只有前台服务可以常驻
     * 9.0之后还需要在Manifest中注册权限 <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
     * */
    private fun starForeServeice() {
        //安卓8.0开启前台服务，与使用通知基本相同
        val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //建立一个通知通道
            val channel = NotificationChannel(foregroundChannelId, foregroundChannelId, NotificationManager.IMPORTANCE_DEFAULT)
            manager.createNotificationChannel(channel)
        }
        //创建一个启动通知的意图
        val intent = Intent(this, MainActivity::class.java)
        val pi = PendingIntent.getActivity(this, 0, intent, 0)
        val notificaion = NotificationCompat.Builder(this, foregroundChannelId)
                .setContentTitle("测试前台服务")
                .setContentText("前台服务正在运行")
                .setContentIntent(pi)
                .build()
        startForeground(1, notificaion)
    }

    //每次启动服务都会调用
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.i(TAG, "onStartCommand: $startId")
        return super.onStartCommand(intent, flags, startId)
    }


    //结束服务的时候
    override fun onDestroy() {
        super.onDestroy()
        isRunning = false
        isBinding = false
        stopThread()
        Log.i(TAG, "onDestroy")
    }
}
